/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import pojo.*;

/**
 *
 * @author DomKvic
 */
public class AccountDAO {
    public static Account getInfo(int idAccount) {
        Session session = util.HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Account acc = (Account) session.get(Account.class, idAccount);
        session.close();
        return acc;
    }
    
    public static Account checkLogin(String email, String pass) {
        Session session = util.HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        String hql = "select s from Account s where s.email = :email and s.pass = :passWord";
        Query query = session.createQuery(hql);
        query.setString("email", email);
        query.setString("passWord", util.MD5.maHoa(pass));
        Object acc = query.uniqueResult();
        if (acc == null) {
            session.close();
            return null;
        }
        session.close();
        return (Account) acc;
    }
    
    public static List<Account> getDS() {
        List<Account> list = null;
        Session session = util.HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        String hql = "from Account";
        Query query = session.createQuery(hql);
        list = query.list();
        session.close();
        return list;
    }
    
    public static boolean SignUp(Account acc) {
        List<Account> list = getDS();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getEmail().equals(acc.getEmail())) {
                return false;
            }
        }
        
        Session session = util.HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            session.save(acc);
            session.getTransaction().commit();
        } catch (Exception ex) {
            session.getTransaction().rollback();
            System.out.println(ex);
            return false;
        }
        finally{
            session.close();
        }
        return true;
    }
    
    public static boolean upDateAcc(Account acc) {
        Session session = util.HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            session.update(acc);
            session.getTransaction().commit();
        } catch (Exception ex) {
            session.getTransaction().rollback();
            System.out.println(ex);
            return false;
        }
        finally{
            session.close();
        }
        return true;
    }
}
